package com.xihuanjun.sdk.dao;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xihuanjun.sdk.entity.SapRequestResult;
import com.xihuanjun.sdk.enums.HttpMethod;
import com.xihuanjun.sdk.enums.SapSLMethod;
import com.xihuanjun.sdk.exception.SapException;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright (C), 2024-08-24
 * FileName: SapViewDao
 * Author:   溪浣君
 * Date:     2024-08-24 13:39
 * Description: 视图操作
 */
@Component
public class SapViewDao extends SapB1SLBaseDao {

    /**
     * 子类必须设置方法类型
     */
    @Override
    protected void setSlMethod() {
        this.slMethod=SapSLMethod.Views;
    }

    public List<LinkedHashMap> execView(String viewName, Map urlParam) throws JsonProcessingException {
        if(viewName.endsWith("B1SLQuery")==false){
            throw new SapException("视图名必须以B1SLQuery结尾");
        }
        SapRequestResult requestResult = this.sendSapRequest("view.svc/" + viewName, HttpMethod.GET, urlParam, null);
        String valueJsonString = this.getValueJsonString(requestResult.getJson());
        ObjectMapper mapper=new ObjectMapper();
        List<LinkedHashMap> ts = mapper.readValue(valueJsonString, new TypeReference<List<LinkedHashMap>>() {
        });
        return ts;
    }

    /**
     * 分页查询一个视图
     * @param viewName 视图名称
     * @param urlParam 筛选条件，key=$filter
     * @param pageIndex 页码
     * @param pageSize 每页条数
     * @return
     * @throws JsonProcessingException
     */
    public List<LinkedHashMap> execViewPage(String viewName, Map urlParam,int pageIndex,int pageSize) throws JsonProcessingException {
        if(viewName.endsWith("B1SLQuery")==false){
            throw new SapException("视图名必须以B1SLQuery结尾");
        }
        if(urlParam==null){
            urlParam=new HashMap();
        }
        this.addPageParam(urlParam,pageIndex,pageSize);
        SapRequestResult requestResult = this.sendSapRequest("/view.svc/" + viewName, HttpMethod.GET, urlParam, null);
        String valueJsonString = this.getValueJsonString(requestResult.getJson());
        ObjectMapper mapper=new ObjectMapper();
        List<LinkedHashMap> ts = mapper.readValue(valueJsonString, new TypeReference<List<LinkedHashMap>>() {
        });
        return ts;
    }
}
